<?php
#[后台通用页信息]
ob_start();
date_default_timezone_set("PRC");
header("Content-type: text/html; charset=utf8");
require_once("config.php");
error_reporting(E_ERROR | E_WARNING | E_PARSE);
set_magic_quotes_runtime(0);
define("PHPOK_SET", TRUE);
$system_time = $systemTime = time();
include_once("version.php");

#[加载字符串处理类]
require_once("class/string.class.php");
$STR = new QG_C_STRING(false,false,false);

$magic_quotes_gpc = get_magic_quotes_gpc();
@extract($STR->format($_POST));
@extract($STR->format($_GET));
if(!$magic_quotes_gpc)
{
	$_FILES = $STR->format($_FILES);
}

require_once("class/mysql.db.class.php");
$DB = new qgSQL($prefix,$dbHost,$dbData,$dbUser,$dbPass,$dbOpenType);

include_once("class/file.class.php");
$FS = new files();
unset($dbHost,$dbData,$dbUser,$dbPass,$dbOpenType);

session_start();

#[加载常用函数]
include_once("include/overall.func.php");
include_once("include/admin.func.php");

#[加载页面类]
require_once("class/page.class.php");
$PA = new pageclass($DB,$prefix,$bi);

#[站点路径]
$siteurlnew = site_uri();
define("SITE_URI",$siteurlnew);
define("SITE_URI_FUL","http://".$_SERVER["HTTP_HOST"].$siteurlnew);

#[新建缓存文件夹]
if(!file_exists("data"))
{
	mkdir("data",0777,true);
}
if(!file_exists("data/admin_tplc"))
{
	mkdir("data/admin_tplc",0777,true);
}
if(!file_exists("data/cache"))
{
	mkdir("data/cache",0777,true);
}

#[加载模板配置]
$set = array
(
	"tplid"=>1,
	"tpldir"=>"admin/tpl",
	"cache"=>"data/admin_tplc",
	"phpdir"=>"",
	"ext"=>"htm",
	"autorefresh"=>true,
	"autoimg"=>true
);
require_once("class/tpl.class.php");
$TPL = new QG_C_TEMPLATE($set);
$TPL->set($set["tplid"],"tplid");
$TPL->set($set["tpldir"],"tpldir");
$TPL->set($set["cache"],"cache");
$TPL->set($set["phpdir"],"phpdir");

#[获取get或post到的变量，并附新值]
$sysfile = $sys_file = $sysFile = SafeHtml($file);
$sysact = $sys_act = $sysAct = SafeHtml($act);

#[判断加载的code]
if($isCheckCode && function_exists("imagecreate") && $sys_act == "chkcode")
{
	ob_clean();
	SetCheckCodes();
	exit;
}

#[后台链接]
$mainlink = "admin.php";
$sysnav = "home";

#[判断会员是否已经登录]
$sys_status = false;
if($_SESSION["admin"]["user"] && $_SESSION["admin"]["pass"])
{
	#[服务器信息]
	$mysql_version = mysql_get_server_info();
	$server_software = $_SERVER["SERVER_SOFTWARE"];
	$server_os = PHP_OS;
	#[管理员名称]
	if($_SESSION["admin"]["typer"]=="system")
	{
		$_SESSION["admin"]["typername"] = "系统管理员";
	}
	elseif($_SESSION["admin"]["typer"]=="manager")
	{
		$_SESSION["admin"]["typername"] = "管理员";
	}
	elseif($_SESSION["admin"]["typer"]=="editor")
	{
		$_SESSION["admin"]["typername"] = "网站编辑";
	}
	if(strpos("login,logout,loginok",$sys_act) === false)
	{
		$sys_status = true;
		#[设置管理员权限]
		if($_SESSION["admin"]["typer"] != "system")
		{
			$adminer_tmp_power = explode(",",$_SESSION["admin"]["modulelist"]);
		}
		else
		{
			$modulelist = "keywords,orderlist,user,link,vote,online,book_feedback,job";
			$adminer_tmp_power = explode(",",$modulelist);
		}
		if(count($adminer_tmp_power)>0)
		{
			foreach($adminer_tmp_power AS $key=>$value)
			{
				$QG_AP[$value] = true;
			}
		}
		unset($adminer_tmp_power);
	}
}

if(!$system && file_exists("data/system_1.php"))
{
	include_once("data/system_1.php");
}
if($system["istonglogin"])
{
	/*单系统请开启*/
	if($_SESSION['admin']){//防止管理员重复登陆；
	//print_r($_SESSION['admin']);
	$sql ="SELECT * FROM ".$prefix."admin WHERE sessionid='".session_id()."' AND id='".$_SESSION['admin']['id']."'";
		$usradmin = $DB->qgCount($sql);
		//die($sql.$usradmin);
		if(!$usradmin){
			unset($_SESSION["admin"]);
			Error("该用户已在其他机器上登录，你被下线！",$mainlink."?act=logout");
		}
	}
}
if($sys_status)
{
	#[这里是弹出窗口的设置]
	$incfile = $STR->safe(rawurldecode($_GET["incfile"]));
	
	#[默认首页]
	if(!$sysFile)
	{
		$sysFile = "index";
	}
	//print_r($sysfile);exit;
	/*if(!$sysfile && !$incfile)
	{
		$TPL->p("home.qg");
		exit;#[中止]
	}*/
	
	if($sysfile && !file_exists("admin/".$sysfile.".qg.php"))
	{
		$TPL->p("nofile.sys");
		exit;
	}
	#[系统组列表]
	$sysmenu = $DB->qgGetAll("SELECT id,groupname,sign FROM ".$prefix."sysgroup ORDER BY taxis ASC,id ASC");
	foreach($sysmenu AS $key=>$value)
	{
		$catelist = $DB->qgGetAll("SELECT * FROM ".$prefix."category WHERE sysgroupid='".$value["id"]."' AND status=1 ORDER BY parentid ASC,taxis ASC,id ASC");
		if($catelist)
		{
			$value["catelist"] = $catelist;
			unset($catelist);
		}
		if($key == count($sysmenu)-1)
		{
			$value["last"] = true;
		}
		$sysmenu[$key] = $value;
	}
	#[加载后台设置的常规配置信息]
	if(!$_SESSION["language"])
	{
		$rsLang = $DB->qgGetOne("SELECT id FROM ".$prefix."lang WHERE ifdefault='1'");
		if(!$rsLang)
		{
			$right_head_language = true;
		}
		$_SESSION["language"] = $rsLang["id"];
		$language = $rsLang["id"];
		unset($rsLang);
	}
	else
	{
		$language = $_SESSION["language"];
	}
	#[如果有参数传递过来]
	if($langid)
	{
		$language = $langid;
		$_SESSION["language"] = $language;
	}
	if(file_exists("data/system_".$language.".php"))
	{
		include_once("data/system_".$language.".php");
	}
	#[加载常规配置]
	if($system)
	{
		#[设置时区]
		if(function_exists("date_default_timezone_set"))
		{
			if(!$system["timezone"])
			{
				$system["timezone"] = "8";
			}
			date_default_timezone_set("Etc/GMT".intval($system["timezone"]));
			//$system_time = $systemTime = $system_now = time() + $system["timerevise"];
			$system_time = $systemTime = mktime(gmdate("H")+$system["timezone"],gmdate("i")+$system["timerevise"],gmdate("s"),gmdate("m"),gmdate("d"),gmdate("Y"));
		}
		else
		{
			$system_time = $systemTime = $system_now = mktime(gmdate("H")+$system["timezone"],gmdate("i")+$system["timerevise"],gmdate("s"),gmdate("m"),gmdate("d"),gmdate("Y"));
		}
		include_once("class/upload.class.php");
		$UP = new UPLOAD("upfiles/".date("Ym/d/",$system_time),"jpg,gif,png,zip,rar,gz");
		include_once("class/gd.class.php");
		$GD = new GD($system["isgd"],$system["gdpic"],$system["gdposition"],$system["thumbwidth"],$system["thumbheight"],$system["markwidth"],$system["markheight"],$system["thumbtype"]);
	}
	else
	{
		$right_head_notice = true;
	}

	if($incfile)
	{
		$site_title = "欢迎进入弹窗页";
		$iframe_height = intval($_GET["iframe_height"]);
		$inputname = $STR->safe($_GET["inputname"]);
		$subtype = intval($_GET["subtype"]);
		if(!$iframe_height)
		{
			$iframe_height = 124;
		}
		$TPL->p("open.index.sys");
		exit;
	}
	require_once("admin/".$sysFile.".qg.php");
	exit;
}

if($act == "loginok")
{
	if(strlen($username)<6) 
	{
		Error("用户名不得少于6位数.",$mainlink."?act=login");
	}

	/*if(!valid_pass($password))
	{
		Error("密码强度不符合后台设定要求.",$mainlink."?act=login");
	}*/
	
	if(!$username || !$password)
	{
		Error("用户名或密码或认证码为空...",$mainlink."?act=login",2,true);
	}
	#[认证码功能]
	if(function_exists("imagecreate") && $isCheckCode)
	{
		if(!$chk)
		{
			Error("验证码不能为空！",$mainlink."?act=login",2,true);
		}
		$chk = md5(strtolower($chk));
		if($chk != $_SESSION["qgLoginChk"])
		{
			Error("认证码输入不正确！",$mainlink."?act=login",2,true);
		}
	}
	
	unset($_SESSION["qgLoginChk"],$chk);
	
	$ip = $_SERVER["REMOTE_ADDR"];
	/*$rows = $DB->qgGetOne("SELECT * FROM ".$prefix."admin WHERE user='".$username."' AND pass='".md5($password)."' LIMIT 1");
	if($rows)
	{
		$_SESSION["admin"] = $rows;
		unset($rows,$password);
		Error("管理员 <strong>".$username."</strong> 登录后台...",$mainlink,2,true);
	}
	else
	{
		Error("管理员账号或密码不正确...",$mainlink."?act=login",2,true);
	}*/
	$rows = $DB->qgGetOne("SELECT * FROM ".$prefix."admin WHERE user='".$username."' AND pass='".md5($password)."' LIMIT 1");
	if($rows)
	{
		//防止管理员重复登陆；
		$sql2 = "UPDATE ".$prefix."admin SET islogin='1',sessionid='".session_id()."' WHERE id='".$rows["id"]."' ";//增加当前登陆的管理员SESSID
		$DB->qgQuery($sql2);
		
		$sql = "SELECT id,state FROM ".$prefix."admin_log WHERE ip='".$ip."' and logindate BETWEEN '".strtotime(date("Y-m-d 00:00:00"))."' AND '".strtotime(date("Y-m-d 23:59:59"))."'  and isstate=0 ";
		$rs = $DB->qgGetOne($sql);
		
		if($rs["state"] > 4)
		{
			Error("您的IP多次登陆失败,请24小时后重试、或致电商友0760-88828816进行解锁...",$mainlink,8);
		}
		$_SESSION["admin"] = $rows;
		unset($rows,$password);
		
		$query = "SELECT * FROM ".$prefix."admin_log WHERE ip='".$ip."' not in (1,2) and logindate BETWEEN '".strtotime(date("Y-m-d 00:00:00"))."' AND '".strtotime(date("Y-m-d 23:59:59"))."'";
		$result=mysql_query($query);
		$number=mysql_num_rows($result);
		
		if($number > 0)
		{
			$sql = "UPDATE ".$prefix."admin_log SET isstate='1',state='0' WHERE ip='".$ip."' and  logindate BETWEEN '".strtotime(date("Y-m-d 00:00:00"))."' AND '".strtotime(date("Y-m-d 23:59:59"))."'";
			$DB->qgQuery($sql);
		}
		else
		{
			$sql = "INSERT INTO ".$prefix."admin_log(ip,logindate,state,isstate) VALUES('".$ip."','".$system_time."','0','1')";
			$DB->qgQuery($sql);
		}
		Error("管理员 <strong>".$username."</strong> 登录后台...",$mainlink,2,true);
	}
	else
	{
		if($rows_logind)
		{
			Error("该管理员被其它用户使用中...",$mainlink."?act=login",2,true);
		}
		else
		{
			$query = "SELECT * FROM ".$prefix."admin_log WHERE ip='".$ip."' and isstate not in (1,2) and logindate BETWEEN '".strtotime(date("Y-m-d 00:00:00"))."' AND '".strtotime(date("Y-m-d 23:59:59"))."'";
			$result=mysql_query($query);
			$number=mysql_num_rows($result);
	
			if($number > 0)
			{
			
				$sql = "SELECT id,state FROM ".$prefix."admin_log WHERE ip='".$ip."' and logindate BETWEEN '".strtotime(date("Y-m-d 00:00:00"))."' AND '".strtotime(date("Y-m-d 23:59:59"))."'  and isstate=0 ";
				$rs = $DB->qgGetOne($sql);
				$state = intval($rs["state"]) + 1;
				
				if($state > 5)
				{
					Error("您的IP多次登陆失败,请24小时后重试、或致电商友0760-88828816进行解锁...",$mainlink,8);
					exit;
				}
				$sql = "UPDATE ".$prefix."admin_log SET logindate='".$system_time."',state='".$state."' WHERE id='".$rs["id"]."'";
				$DB->qgQuery($sql);
				
				unset($rs);
			}
			else
			{
				$sql = "INSERT INTO ".$prefix."admin_log(ip,logindate,state,isstate) VALUES('".$ip."','".$system_time."','0','0')";
	
				$DB->qgQuery($sql);
			}
			Error("管理员账号或密码不正确...",$mainlink."?act=login",2,true);
		}
	}
}
elseif($act == "logout")
{
	$sql2 = "UPDATE ".$prefix."admin SET islogin='0' WHERE id='".$_SESSION["admin"]["id"]."' ";
	$DB->qgQuery($sql2);

	session_destroy();
	
	$ip = $_SERVER["REMOTE_ADDR"];
	
	$sql = "INSERT INTO ".$prefix."admin_log(ip,logindate,isstate) VALUES('".$ip."','".$system_time."','2')";

	$DB->qgQuery($sql);
	$_SESSION='';
	Error("管理员成功退出...",$mainlink."?act=login");
}
else
{
	Foot("login.sys");
}


function valid_pass($candidate) {  
    /*$r1='/[A-Z]/';  //uppercase  */
    $r2='/[a-zA-Z]/';  //lowercase  
    $r3='/[0-9]/';  //numbers  
    $r4='/[~!@#$%^&*()\-_=+{};:<,.>?]/';  // special char  
  	/*
    if(preg_match_all($r1,$candidate, $o)<1) {  
        //echo "密码必须包含至少一个大写字母，请返回修改！<br />";  
        return FALSE;  
    } */ 
    if(preg_match_all($r2,$candidate, $o)<1) {  
        //echo "密码必须包含至少一个小写字母，请返回修改！<br />";  
        return FALSE;  
    }  
    if(preg_match_all($r3,$candidate, $o)<1) {  
        //echo "密码必须包含至少一个数字，请返回修改！<br />";  
        return FALSE;  
    }  
    if(preg_match_all($r4,$candidate, $o)<1) {  
        //echo "密码必须包含至少一个特殊符号：[~!@#$%^&*()\-_=+{};:<,.>?]，请返回修改！<br />";  
        return FALSE;  
    }  
    if(strlen($candidate)<8) {  
        //echo "密码必须包含至少含有8个字符，请返回修改！<br />";  
        return FALSE;  
    }  
    return TRUE;  
}     

if(isset($_SESSION["expiretime"])) {
    if($_SESSION["expiretime"] < time()) {
        unset($_SESSION['expiretime']);
        header("Location: ".$mainlink."?act=logout"); // 登出
        exit(0);
    } else {
        $_SESSION["expiretime"] = time() + 3600; // 刷新时间戳1小时
    }
}
?>